﻿using NCP.Core;
using NCP.Core.Extensions;
using NCP.Model;
using NCP.Service;
using NCP.Util;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using WebApp.Filters;
using System.Management;
using System.Text;
using System.Security.Cryptography;
using System.Web.UI.WebControls;
using NCP.Core.DataUtil;
using SqlSugar;
using System.Configuration;

namespace WebApp.Controllers
{
    public class HomeController : Controller
    {
        private MemberService _mService;
        private PermissionService _pmsService;

        public HomeController(MemberService mService, PermissionService pmsService)
        {
            _mService = mService;
            _pmsService = pmsService;
        }
        [Authen]
        public ActionResult Index()
        {
            ViewData["username"] = MemberUtil.CurrentMember.Name;
            return View();
        }

        [Authen]
        public ActionResult GetMenuData()
        {
            List<Permission> pmsList = _pmsService.GetPmsByUserCode(MemberUtil.CurrentMember.Code, MemberUtil.CurrentMember.IsSysAdmin);
            List<MenuData> menus = new List<MenuData>();
            foreach (Permission pms in pmsList)
            {
                MenuData menuData = BuildMenu(pms);
               
                menus.Add(menuData);
            }
            return Json(menus);
        }

        public MenuData BuildMenu(Permission pms)
        {
            MenuData menuData = new MenuData();
            menuData.id = pms.Id;
            menuData.title = pms.PmsName;
            menuData.href = "";
            menuData.icon = "layui-icon layui-icon-console";
            menuData.type = pms.SubPermissionList == null || pms.SubPermissionList.Count == 0 ? 1 : 0;
            menuData.openType = pms.SubPermissionList == null || pms.SubPermissionList.Count == 0?"_iframe":"";
            menuData.href= pms.SubPermissionList == null || pms.SubPermissionList.Count == 0 ? pms.PmsAddr : "";
            menuData.children=new List<MenuData>();
            if (pms.SubPermissionList != null)
            {
                foreach (var p in pms.SubPermissionList)
                {
                    MenuData menu = new MenuData();
                    menu = BuildMenu(p);
                    menuData.children.Add(menu);
                }
            }
            return menuData;
        }

        public ActionResult TransferLogin()
        {
            return View();
        }

        public ActionResult sLogin()
        {
            return View();
        }

        public ActionResult aLogin()
        {
            //string username = Encryption.DecodeBase64("utf-8", Request["username"]);
            //string pwd = Encryption.DecodeBase64("utf-8", Request["password"]);
            //bool issuc = false;
            //Member m = _mService.Login(username, HashEncrypt.Md5Hash(pwd), out issuc);
            //if (m != null && issuc)
            //{
            //    Session[Keys.UserID.ToString()] = m.Id;
            //    Session[Keys.User.ToString()] = m;
            //    HttpCookie myUserId = new HttpCookie(Keys.UserID.ToString());
            //    myUserId.Value = EncryptionDes.Encrypt(m.Id.ToString());
            //    myUserId.HttpOnly = true;
            //    myUserId.Expires = DateTime.Now.AddHours(3);
            //    Response.Cookies.Add(myUserId);

            //    LayData rst = new LayData("0", "登陆成功");

            //    return Json(rst, JsonRequestBehavior.AllowGet);
            //}
            //LayData rst1 = new LayData("1", "用户名或密码错误");

            //return Json(rst1, JsonRequestBehavior.AllowGet);
            string username = Encryption.DecodeBase64("utf-8", Request["username"]);
            string pwd = Encryption.DecodeBase64("utf-8", Request["password"]);
            bool issuc = false;
            Member m = _mService.Login(username, HashEncrypt.Md5Hash(pwd), out issuc);
            Config config = _mService.GetRegisterValue("register");
            NCP.Util.PublicUtil publicUtil = new PublicUtil();
            string zcm = publicUtil.getRNum();
            //如果未注册则登录不了
            if (config.value != zcm && "1"!="1") //
            {
                LayData rst2 = new LayData("1", "系统尚未注册，请联系管理员");
                return Json(rst2, JsonRequestBehavior.AllowGet);
            }
            else
            {
                if (m != null && issuc)
                {
                    Session[Keys.UserID.ToString()] = m.Id;
                    Session[Keys.User.ToString()] = m;
                    HttpCookie myUserId = new HttpCookie(Keys.UserID.ToString());
                    myUserId.Value = EncryptionDes.Encrypt(m.Id.ToString());
                    myUserId.HttpOnly = true;
                    myUserId.Expires = DateTime.Now.AddHours(3);
                    Response.Cookies.Add(myUserId);

                    LayData rst = new LayData("0", "登陆成功");

                    return Json(rst, JsonRequestBehavior.AllowGet);
                }
                LayData rst1 = new LayData("1", "用户名或密码错误");
                return Json(rst1, JsonRequestBehavior.AllowGet);
            }

        }

        public ActionResult LogOut()
        {
            HttpCookie myCookie = Request.Cookies[Keys.UserID.ToString()];
            if (myCookie != null)
            {
                myCookie.Value = "";
                myCookie.Expires = DateTime.Now.AddYears(-2);
                Response.Cookies.Add(myCookie);
            }
            Session[Keys.UserID.ToString()] = null;
            Session[Keys.User.ToString()] = null;

            return Redirect("/Home/sLogin");
        }

        public ActionResult Welcome()
        {
            return View();
        }
        public ActionResult NoPms()
        {
            return View();
        }

        //预警
        public ActionResult EarlyWarn() 
        {
            string IsAllMissionDeptOper = ConfigurationManager.AppSettings["IsAllMissionDeptOper"].ToString();//获取是否查看全部科室任务量
            string GetRoleSql = string.Format(" select e.RoleCode from MemberInRole l left join Role e on e.Id = l.RoleId where l.Code = '{0}'", MemberUtil.CurrentMember.Code);//根据工号获取角色
            SqlSugarClient _client = DbHelper.GetSqlSugarClient();
            string role = _client.Ado.GetString(GetRoleSql);
            ViewData["IsSys"] = IsAllMissionDeptOper.IndexOf(role) < 0 ? "0" : "1";
            return View();
        }
      
    }
}